//
//  CZRefreshControl.swift
//  weibo
//
//  Created by Apple on 16/3/16.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  设置控件的高度
let RefreshControlHeight: CGFloat = 50

/*
    1.Normal 默认状态
    2.Pulling 松手就刷新状态（将要刷新）
    3.Refreshing 正在刷新状态
*/
//  定义刷新状态
enum CZRefreshControlState :Int {
    case Normal = 1
    case Pulling = 2
    case Refreshing = 3
}

//  封装下拉刷新控件
class CZRefreshControl: UIControl {
    
    //  当前控件的刷新状态
    var czState: CZRefreshControlState = .Normal {
        didSet {
            switch czState {
            case .Normal:
                //  显示箭头，需要重置默认箭头位置，菊花动画停止，文字显示下拉起飞
                messageLabel.text = "下拉起飞"
                iconView.hidden = false
                indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformIdentity
                })
                //  如果上次的值是刷新状态contentInset.top设置成原始的位置
                if oldValue == .Refreshing {
                   
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshControlHeight
                    })
                }
                
                print("下拉起飞")
                
            case .Pulling:
                //  箭头掉转，文字显示‘松手起飞’
                messageLabel.text = "松手起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                print("松手起飞")
                
            case .Refreshing:
                //  箭头隐藏，菊花动画开启，文字显示’正在起飞‘
                messageLabel.text = "正在起飞"
                iconView.hidden = true
                indicatorView.startAnimating()
                print("松手起飞")
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += RefreshControlHeight
                })
                
                //  发送事件
                sendActionsForControlEvents(.ValueChanged)
                
            }
        }
    }
    //  记录获取的scrollview
    var scrollView: UIScrollView?
    
    // MARK:    懒加载控件
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  消息文本
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        label.text = "下拉起飞"
        return label
    }()
    //  风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.greenColor()
       
        
        //  添加控件
        addSubview(iconView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        //  设置约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconView.snp_trailing)
            make.centerY.equalTo(iconView)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView)
            make.centerY.equalTo(iconView)
        }
        
    }
    
    //  获取添加的父控件,监听父控件的滚动
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let scrollView = newSuperview as? UIScrollView {
            //  设置frame根据scrollview的大小
            self.frame.size = CGSize(width: scrollView.frame.width, height: RefreshControlHeight)
            self.frame.origin.y = -RefreshControlHeight
            
            self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
        }
    }
    //  kvo 监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //  意思是显示的内容top距离frame顶部的距离
       // print(scrollView!.contentInset.top)
        //print(change)
        
        
        //  判断是否在拖动
        if scrollView!.dragging {
            //  改变状态的临界值
            let changeStateContentOffsetY = -scrollView!.contentInset.top-RefreshControlHeight
            //  scrollview滚动的y轴偏移量
            let contentOffsetY = scrollView!.contentOffset.y
            //  如果滚动的偏移量小于临界点说明 往下拖动的多，因为是负数，约往下拖动越小
            if czState == .Normal && contentOffsetY < changeStateContentOffsetY {
                //  进入松手即刷新状态
                print("进入松手即刷新状态")
                czState = .Pulling
            } else if czState == .Pulling && contentOffsetY >= changeStateContentOffsetY {
                //  进入默认状态
                print("进入默认状态")
                czState = .Normal
            }
        } else {
            //  改成正在刷新状态有两个条件，
            //  1.首先 松手
            //  2.当前状态是Pulling，满足这两个条件进入正在刷新状态
            if czState == .Pulling {
                czState = .Refreshing
                print("进入正在刷新状态")
            }
        }
        
        
    }
    
    //  结束动画
    func endRefreshing() {
        czState = .Normal
    }
    
    
    deinit {
        //  移除kvo
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
